package cn.wit.summit.chwan.ui.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.webkit.DownloadListener;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.wit.summit.chwan.R;
import cn.wit.summit.chwan.models.dto.IntentDataBean;
import cn.wit.summit.chwan.models.dto.WebAccountDataBean;
import cn.wit.summit.chwan.tools.webview.WebJSPInterfaceMethedBean;
import cn.wit.summit.chwan.tools.webview.WebViewClientYQW;
import cn.wit.summit.chwan.ui.base.MyActivity;
import cn.wit.summit.chwan.utils.AccountBean;
import cn.wit.summit.chwan.utils.AccountUtil;
import cn.wit.summit.chwan.utils.JsonMapper;
import cn.wit.summit.chwan.utils.NetWorkUtils;
import cn.wit.summit.chwan.utils.StringUtils;
import cn.wit.summit.chwan.utils.ToastUtils;
import cn.wit.summit.chwan.utils.UtilsMy;
import cn.wit.summit.chwan.widgets.LJWebView;
import cn.wit.summit.chwan.widgets.SoftKeyBoardListener;


/**
 * Created by pengsk on 2015/2/12.
 */
public class ShareWebActivity extends MyActivity implements LJWebView.FindMethod {

    public static final int LOCATION_PERMISSION_REQ_CODE = 1;
    public static final int WRITE_PERMISSION_REQ_CODE = 2;

    String TAG = "ShareWebActivity";
    @Bind(R.id.shareWebRootRl)
    RelativeLayout shareWebRootRl;
    private String INTENT_EXTRA_ACTION_FROM = "PAPA_EMU_INTENT_EXTRA_ACTION_FROM";//模拟器跳转过来,去开通VIP
    private Handler mHandler = new Handler();
    @Bind(R.id.loding_layout)
    LinearLayout loding_layout;
    @Bind(R.id.loding_faile)
    LinearLayout loding_faile;
    @Bind(R.id.failedMessage)
    TextView failedMessage;
    @Bind(R.id.video_view)
    FrameLayout video_view;
    @Bind(R.id.weblayout)
    RelativeLayout weblayout;
    @Bind(R.id.bar_title_tx)
    TextView title_textview;
    @Bind(R.id.web)
    LJWebView web;

    private String url;
    private String urlFirst;
    private long lastClick;
    private Activity context;
    //是错误过来的。。
    private boolean isError = false;
    private AccountBean accountBean;
    private boolean startLogling = false;

    IntentDataBean intentdate;
    private View xCustomView;
    private int defaultScreenState = 0;
    private WebChromeClient chromeClient;

    private boolean hasdestroy = false;

    private boolean mPermission;


    void refresh() {
        lodeWebView(url);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        try {
            setContentView(R.layout.share_activity_layout);
            ButterKnife.bind(this);
            if (savedInstanceState != null && web != null) {
                web.getWebView().restoreState(savedInstanceState);
            }
            intentdate = (IntentDataBean) getIntent().getSerializableExtra("intentData");
            afterview();
        } catch (Exception e) {
            e.printStackTrace();
        }

        SoftKeyBoardListener.setListener(mAty, new SoftKeyBoardListener.OnSoftKeyBoardChangeListener() {
            @Override
            public void keyBoardShow(final int height) {
                disHeight = height - disH;
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Message message = new Message();
                        message.what = 1;
                        handler.sendMessage(message);
                    }
                }, 100);
            }

            @Override
            public void keyBoardHide(int height) {
                disHeight = 0;
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) shareWebRootRl.getLayoutParams();
                        params.topMargin = 0;
                        shareWebRootRl.setLayoutParams(params);
                    }
                }, 100);
            }
        });
    }

    private int disH = 150;
    private int disHeight = 0;
    private int tempHeight = 0;
    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) shareWebRootRl.getLayoutParams();
                    params.topMargin = -disHeight;
                    shareWebRootRl.setLayoutParams(params);
                    tempHeight += 20;
                    if (tempHeight < disHeight) {
                        Message message = new Message();
                        message.what = 1;
                        handler.sendMessageDelayed(message, 50);
                    } else {
                        Message message = new Message();
                        message.what = 11;
                        handler.sendMessageDelayed(message, 50);
                    }
                    break;
                case 11:
                    LinearLayout.LayoutParams paramsShow = (LinearLayout.LayoutParams) shareWebRootRl.getLayoutParams();
                    paramsShow.topMargin = -disHeight;
                    shareWebRootRl.setLayoutParams(paramsShow);
                    break;
            }
            super.handleMessage(msg);
        }
    };

    boolean isFromEmu = false;


    void afterview() {

        try {
            context = this;

            final IntentDataBean intentDateBean = intentdate;
            url = intentDateBean.getJump_link_type_val();
            urlFirst = intentDateBean.getJump_link_type_val();


            if (url == null) {
                url = "";
            }
            if (!url.contains("http://") && !url.contains("file://") && !url.contains("https://")) {
                url = "http://" + url;
            }
            lodeWebView(url);

            if (failedMessage != null)
                failedMessage.setText("网页加载失败，再试试吧~");
            //添加监听
            if (web != null)
                web.setMethodListenter(this);
//            dialog = DialogUtil_.getInstance_(context).getLodingDialog(context);
//
//            mPermission = checkPublishPermission();
            web.getWebView().setDownloadListener(new DownloadListener() {
                @Override
                public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {

                    UtilsMy.downFileFromWeb(context, url, System.currentTimeMillis() + "");

                }
            });
            barBackLl.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (inCustomView()) {
                        chromeClient.onHideCustomView();
                        return;
                    }

                    if (StringUtils.isNotEmpty(urlFirst) && urlFirst.equals(url)) {
                        finish();
                    }
                    WebView w = web.getWebView();
                    if (w != null && NetWorkUtils.isNetworkConnected(context)) {
                        w.loadUrl("javascript:papaBackPageUp()");
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        web.loadUrl("javascript:papaActivityOnResume()");
        if (web != null) {
            try {
                web.getWebView().getClass().getMethod("onResume").invoke(web.getWebView(), (Object[]) null);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
        }
        accountBean = AccountUtil.getInstance().getAccountData();
        if (startLogling) {
            if (web != null) {
                WebAccountDataBean webAccountDataBean = new WebAccountDataBean();
                if (accountBean != null) {
                    webAccountDataBean.setHasLogin(true);
                    webAccountDataBean.setAccountBean(accountBean);
                } else {
                    webAccountDataBean.setHasLogin(false);
                    webAccountDataBean.setAccountBean(accountBean);
                }
                web.loadUrl("javascript:papaPutAccountData(" + JsonMapper.getInstance().toJson(webAccountDataBean) + ")");
            }
            startLogling = false;
        }
    }

    @Override
    protected void onPause() {
        if (web != null) {
            try {
                web.getWebView().getClass().getMethod("onPause").invoke(web.getWebView(), (Object[]) null);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }

        }
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        hasdestroy = true;
        web.loadUrl("");
//        ButterKnife.unbind(this);
        super.onDestroy();
    }

    void showLoding() {
        try {
            loding_layout.setVisibility(View.GONE);
            loding_faile.setVisibility(View.GONE);
            if (web != null)
                web.setVisibility(View.VISIBLE);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    void showLodingFailed() {

        try {
            loding_faile.setVisibility(View.VISIBLE);
            loding_layout.setVisibility(View.GONE);
            if (web != null)
                web.setVisibility(View.GONE);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    void showMain() {

        try {
            loding_faile.setVisibility(View.GONE);
            loding_layout.setVisibility(View.GONE);
            if (web != null)
                web.setVisibility(View.VISIBLE);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    void loding_faile() {
        if (web != null) {
            isError = false;
            lodeWebView(url);
        }
    }

    private void lodeWebView(String url) {
        try {
            if (NetWorkUtils.isNetworkConnected(this)) {
                if (web == null) return;

                web.setVisibility(View.VISIBLE);
                web.setBarHeight(getResources().getDimensionPixelOffset(R.dimen.wdp6));
                web.setClickable(true);
                web.setUseWideViewPort(true);
                web.setSupportZoom(false);
                web.setBuiltInZoomControls(false);
                web.setJavaScriptEnabled(true);
                web.setCacheMode(WebSettings.LOAD_DEFAULT);

                web.setWebViewClient(new WebViewClientYQW(ShareWebActivity.this, new WebViewClientYQW.WebViewClientInterface() {
                    @Override
                    public void setUrl(String url) {
                        ShareWebActivity.this.url = url;
                    }

                    @Override
                    public void showLoding() {
                        mHandler.post(new Runnable() {
                            public void run() {
                                showLoding();
                            }
                        });
                    }

                    @Override
                    public void showLodingFailed() {
                        mHandler.post(new Runnable() {
                            public void run() {
                                showLodingFailed();
                            }
                        });
                    }
                }));

                web.addJavascriptInterface(new WebJSPInterfaceMethedBean(this, web.getWebView(), new WebJSPInterfaceMethedBean.WebJsInterface() {
                    @Override
                    public void showTitle(final boolean showTile) {
                        mHandler.post(new Runnable() {
                            public void run() {
                                if (showTile) {
                                    showTitleBar();
                                } else {
                                    hideTitleBar();
                                }

                            }
                        });
                    }

                    @Override
                    public void setTitleText(final String titleText) {
                        mHandler.post(new Runnable() {
                            public void run() {
                                title_textview.setText(titleText);
                            }
                        });
                    }

                    @Override
                    public void setFullScreen(final boolean isfullScreen) {
                        mHandler.post(new Runnable() {
                            public void run() {
                                if (isfullScreen) {
                                    ShareWebActivity.this.setFullScreen();
                                } else {
                                    quitFullScreen();
                                }

                            }
                        });
                    }
                }));
//                web.addJavascriptInterfacewufan(new WebJSPInterfaceMethedBeanWufan());
                web.loadUrl(url);
            } else {
                showLodingFailed();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    void showTost(String message) {
        ToastUtils.getInstance(context).showToastSystem(message);
    }


    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            if (inCustomView()) {
                chromeClient.onHideCustomView();
                return true;
            }

            if (StringUtils.isNotEmpty(urlFirst) && urlFirst.equals(url)) {
                finish();
            }
            WebView w = web.getWebView();
            if (w != null && NetWorkUtils.isNetworkConnected(this)) {
                w.loadUrl("javascript:papaBackPageUp()");
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 没有当前方法
     */
    @Override
    public void noMethod() {
//如果是已经开始back则表示是点击了返回按钮后发生的是返回事件

        WebView w = web.getWebView();
        if (w != null && w.canGoBack()) {
            w.goBack();
        } else {
//            if (isTaskRoot()&&intentDataMain == null) {
//                Intent intent = new Intent();
//                intent.setClass(ShareWebActivity.this, com.join.mgps.activity.MGMainActivity_.class);
//                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
//                startActivity(intent);
//            }
            finish();
        }

    }

    @Override
    public void onShowCustomView(View view, WebChromeClient.CustomViewCallback customViewCallback, WebChromeClient chromeClient) {
        // 设置webView隐藏
        xCustomView = view;
        if (view == null) return;
//        else if (customViewCallback != null) {
//            this.customViewCallback = customViewCallback;
//        }
        this.chromeClient = chromeClient;
        weblayout.setVisibility(View.GONE);
//        title.setVisibility(View.GONE);
//        // 声明video，把之后的视频放到这里面去
//        video.removeAllViews();
//        video.setVisibility(View.VISIBLE);
//        // 将video放到当前视图中
//        video.addView(view, new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT));
        // 横屏显示
//        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        // 设置全屏
//        setFullScreen();
    }

    @Override
    public void onHideCustomView() {
        xCustomView = null;
        // 用户当前的首选方向
//        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_USER);
        // 退出全屏  恢复原来的屏幕状态
        quitFullScreen();
        // 设置WebView可见

    }

    @Override
    public void showMainWebview() {
        if (loding_faile != null)
            loding_faile.setVisibility(View.GONE);
        if (loding_layout != null)
            loding_layout.setVisibility(View.GONE);
        if (web != null && web.getVisibility() != View.VISIBLE) {
            showMain();
        }
    }

    @Override
    public void onReceivedTitle(String title) {
    }

    /**
     * 设置全屏
     */
    private void setFullScreen() {
        // 设置全屏的相关属性，获取当前的屏幕状态，然后设置全屏
//        WindowManager.LayoutParams params = getWindow().getAttributes();
//        params.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
//        getWindow().setAttributes(params);
//        getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        // 全屏下的状态码：1098974464
        // 窗口下的状态吗：1098973440
    }

    /**
     * 退出全屏
     */
    private void quitFullScreen() {
//        // 声明当前屏幕状态的参数并获取
//        video.setVisibility(View.GONE);
//        weblayout.setVisibility(View.VISIBLE);
//        title.setVisibility(View.VISIBLE);
////        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_USER);
//        switch (defaultScreenState) {
//            case 0:
//                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
//                break;
//            case 1:
//                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
//                break;
//            case 2:
//                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
//                break;
//        }
//        final WindowManager.LayoutParams attrs = getWindow().getAttributes();
//        attrs.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
//        getWindow().setAttributes(attrs);
//        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
    }

    /**
     * 判断是否是全屏
     *
     * @return
     */
    public boolean inCustomView() {
        return (xCustomView != null);
    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        web.getWebView().saveState(outState);
    }

    private class WebViewClientXY extends WebViewClient {
//        private Dialog progressDialog;

        public WebViewClientXY(Context context) {


        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url2) {

            if (NetWorkUtils.isNetworkConnected(context)) {
                if (!url2.startsWith("weixin:")) {
                    if (url2.startsWith("http") || url2.startsWith("https") || url2.startsWith("file://")) {
                        url = url2;
                    } else {
                        try {
                            startActivity(new Intent("android.intent.action.VIEW", Uri.parse(url2)));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        return true;
                    }
                    return super.shouldOverrideUrlLoading(view, url2);

                } else {
                    try {
                        startActivity(new Intent("android.intent.action.VIEW", Uri.parse(url2)));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            } else {
            }
            return true;
        }

        @Override
        public void onPageStarted(WebView view, String url2, Bitmap favicon) {
            super.onPageStarted(view, url2, favicon);

            if (url2.startsWith("http") || url2.startsWith("https") || url2.startsWith("file://")) {
//                view.loadUrl(url);// 当打开新链接时，使用当前的 WebView，不会使用系统其他浏览器
                url = url2;//记录url
            }
            showLoding();
        }

        @Override
        public void onPageFinished(WebView view, String url2) {
            super.onPageFinished(view, url2);
            if (url2.startsWith("http") || url2.startsWith("https") || url2.startsWith("file://")) {
//                view.loadUrl(url);// 当打开新链接时，使用当前的 WebView，不会使用系统其他浏览器
                url = url2;//记录url
            }
            //显示默认的失败界面的url
            if (url.equals("data:text/html,chromewebdata") || isError) {
                showLodingFailed();
                return;
            }
            view.getSettings().setBlockNetworkImage(false);
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
            isError = true;
            view.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
            showLodingFailed();
        }
    }


    /******************************************************/


    AccountUtil accountUtil;


    private AccountBean accountBean(Context ctx) {
        return AccountUtil.getInstance().getAccountData();
    }


    /******************************************************/


    private Dialog mPicChsDialog;
    private Uri fileUri, cropUri;
    private static final int CAPTURE_IMAGE_CAMERA = 100;
    private static final int IMAGE_STORE = 200;
    private static final int CROP_CHOOSE = 10;
    private boolean mUploading = false;


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case LOCATION_PERMISSION_REQ_CODE:
//                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//                    if (!TCLocationHelper.getMyLocation(this, this)) {
//                        tvLBS.setText(getString(com.tencent.qcloud.xiaozhibo.R.string.text_live_lbs_fail));
//                        btnLBS.setChecked(false, false);
//                    }
//                }
                break;
            case WRITE_PERMISSION_REQ_CODE:
                for (int ret : grantResults) {
                    if (ret != PackageManager.PERMISSION_GRANTED) {
                        return;
                    }
                }
                mPermission = true;
                break;
            default:
                break;
        }
    }
//
//    private boolean checkPublishPermission() {
//        if (Build.VERSION.SDK_INT >= 23) {
//            List<String> permissions = new ArrayList<>();
//            if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
//                permissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
//            }
//            if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA)) {
//                permissions.add(Manifest.permission.CAMERA);
//            }
//            if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE)) {
//                permissions.add(Manifest.permission.READ_PHONE_STATE);
//            }
//            if (permissions.size() != 0) {
//                ActivityCompat.requestPermissions(this,
//                        permissions.toArray(new String[0]),
//                        WRITE_PERMISSION_REQ_CODE);
//                return false;
//            }
//        }
//
//        return true;
//    }


    private List<String> uploadImages = new ArrayList<>();


    //endregion
}